<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Active;
use app\common\model\AdminLog;
use app\common\model\AuthRule;
use app\common\model\Brand;
use app\common\model\Browse;
use app\common\model\Com;
use app\common\model\Evaluation;
use app\common\model\Forum;
use app\common\model\ForumMedia;
use app\common\model\GirlImg;
use app\common\model\Knowledge;
use app\common\model\Label;
use app\common\model\LoginRecord;
use app\common\model\Material;
use app\common\model\NewFlash;
use app\common\model\Platform;
use app\common\model\Slide;
use app\common\model\User;
use org\Auth;
use think\Db;
use think\helper\Time;
use think\Request;
use think\Session;
use Zhuzhichao\IpLocationZh\Ip;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Index extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {

        $version = Db::query('SELECT VERSION() AS ver');
        $config  = [
            'url' => $_SERVER['HTTP_HOST'],
            'document_root' => $_SERVER['DOCUMENT_ROOT'],
            'server_os' => PHP_OS,
            'server_port' => $_SERVER['SERVER_PORT'],
            'server_soft' => $_SERVER['SERVER_SOFTWARE'],
            'php_version' => PHP_VERSION,
            'mysql_version' => $version[0]['ver'],
            'timezone' => date_default_timezone_get(),
            'max_upload_size' => ini_get('upload_max_filesize')
        ];

        return view('index', compact('config'));
    }


    /**
     * @param Request $request
     * 系统首页
     */
    public function webRecord(Request $request)
    {
        $where              = [];
        $platform           = $request->param('platform') ?: 3;
        $start_time         = $request->param('start_time') ?: '';
        $end_time           = $request->param('end_time') ?: '';
        $excel_export       = $request->param('excel_export') ?: 0;
        $map                = [];
        $where_time         = [];
        $where_com          = [];
        $where_login_record = [];

        if ($start_time && $end_time) {
            $time1                           = strtotime($start_time);
            $time2                           = strtotime($end_time);
            $where['car_browse.create_time'] = ['between', "$time1,$time2"];
        }

        if ($start_time && $end_time) {
            $time1                            = strtotime($start_time);
            $time2                            = strtotime($end_time);
            $where_com['car_com.create_time'] = ['between', "$time1,$time2"];
        }
        if ($platform) {
            $map['platform'] = $platform;
        }

        if ($platform) {
            if ($platform == 1) {
                $where_login_record['type'] = 2;
            } else {
                $where_login_record['type'] = 1;
            }
        }
        if ($start_time && $end_time) {
            $where_time['create_time'] = ['between', "$start_time,$end_time"];
        }

        //加入统计
        list($start, $end) = Time::today();
        $data['login_user']       = User::where($where_time)->where($map)->where('update_time', '>=',
            $start)->where('update_time', '<',
            $end)->count('id');
        $data['all_user_num']     = User::where($where_time)->where($map)->count('id');
        $data['all_user_read']    = Browse::where($map)->where($where)->count('id');
        $data['all_user_comment'] = Com::where($where_com)
            ->where('car_user.platform', $platform)
            ->join('car_user', 'car_user.id = car_com.uid', 'LEFT')
            ->count('car_com.id');
        $data['video_play_num']   = Browse::where($map)->where($where)
            ->whereNotNull('car_forum_media.video_url')
            ->join('car_forum_media', 'car_forum_media.forum_id = car_browse.forum_id', 'LEFT')
            ->count('car_browse.forum_id');
        $data['video_play_time']  = ForumMedia::where(1)
            ->where('car_browse.platform', $platform)
            ->whereNotNull('car_forum_media.video_url')
            ->join('car_browse', 'car_browse.forum_id = car_forum_media.forum_id', 'LEFT')
            ->sum('car_forum_media.video_time');

        //留存率公式：第N日该批用户登录数量/当日注册用户数量
        $time_now = strtotime(date('Y-m-d', time()));
        $dayago3  = Time::daysAgo(1);
        $dayago7  = Time::daysAgo(7);
        $dayago30 = Time::daysAgo(30);
        //当日注册用户

        $dayago3_user = count(LoginRecord::where('car_login_record.create_time', '>=', $dayago3)
            ->where('car_login_record.create_time', '<',
                $time_now)->where('car_user.platform', $platform)
            ->join('car_user', 'car_user.id = car_login_record.user_id', 'LEFT')
            ->distinct(true)
            ->field(['car_login_record.user_id'])
            ->select());

        $dayago7_user = count(LoginRecord::where('car_login_record.create_time', '>=', $dayago7)
            ->where('car_login_record.create_time', '<',
                $time_now)
            ->where('car_user.platform', $platform)
            ->join('car_user', 'car_user.id = car_login_record.user_id', 'LEFT')
            ->distinct(true)
            ->field(['car_login_record.user_id'])
            ->select());

        $dayago30_user         = count(LoginRecord::where('car_login_record.create_time', '>=', $dayago30)
            ->where('car_login_record.create_time', '<',
                $time_now)
            ->where('car_user.platform', $platform)
            ->join('car_user', 'car_user.id = car_login_record.user_id', 'LEFT')
            ->distinct(true)
            ->field(['car_login_record.user_id'])
            ->select());
        $time_now_date         = date('Y-m-d H:i:s', $time_now);
        $today_reg_user        = User::where('create_time', '>', $time_now_date)->count('id');
        $data['user_exist_3']  = empty($today_reg_user) ? 0 : ($dayago3_user / $today_reg_user);
        $data['user_exist_7']  = empty($today_reg_user) ? 0 : ($dayago7_user / $today_reg_user);
        $data['user_exist_30'] = empty($today_reg_user) ? 0 : ($dayago30_user / $today_reg_user);

        if ($excel_export) {
            $xlsName = "首页数据";
            $xlsCell = array(
                array('login_user', '登录用户人数'),
                array('all_user_num', '注册用户人数'),
                array('all_user_read', '用户阅读量'),
                array('all_user_comment', '用户评价量'),
                array(
                    'video_play_num',
                    '视频播放量
'
                ),
                array('video_play_time', '视频播放时长'),
                array('user_exist_3', '次日留存'),
                array('user_exist_7', '7次留存'),
                array('user_exist_30', '30日留存'),
            );

            $xlsData   = [];
            $xlsData[] = $data;
            exportExcel($xlsName, $xlsCell, $xlsData);
        }

        $platform_arr = Platform::all();
        foreach ($data as &$value) {
            $value = FormatMoney($value);
            if (strpos($value, '.')) {
                $value = $value . '万';
            }
        }
        return view('webrecord', compact('data', 'platform', 'platform_arr', 'start_time', 'end_time'));

    }

    public function notFound()
    {
        return view('404');
    }

    /**
     * @param Request $request
     * @return \think\response\View
     * 登录列表
     */
    public function loginRecord(Request $request)
    {

        $limit= $request->param('limit');
        $page= $request->param('page');
        $login_all = AdminLog::where(1)
            ->join('car_admin_user','car_admin_user.id = car_admin_log.admin_user_id')
            ->field(['car_admin_log.create_time', 'car_admin_user.id', 'car_admin_user.real_name', 'car_admin_user.username', 'car_admin_user.mobile','car_admin_log.login_ip'])
            ->paginate($limit,false,['page'=>$page]);
        foreach ($login_all as $item=>$value){
            $login_all[$item]['area'] = getIpAddress($value['login_ip']);
        }

        return view('loginRecord',compact('login_all'));
    }




    /**
     * 更改上线状态
        1	资讯
        2	视频
        3	测评
        4	活动
        5	快讯
        6	音频
        7	图片
     */
    public function updateOnlineType(Request $request)
    {
        $status = $request->param('status');
        $id     = $request->param('id');
        $type   = $request->param('type');

        switch ($type) {
            case 1:
                $result = Knowledge::where('id', $id)->update(['online_type' => $status]);
                break;
            case 2:
            case 6:
                $result = Forum::where('id', $id)->update(['status' => $status]);
                break;
            case 3:
                $result = Evaluation::where('id', $id)->update(['status' => $status]);
                break;
            case 4:
                $result = Active::where('id', $id)->update(['is_up' => $status]);
                break;
            case 5:
                $result = NewFlash::where('id', $id)->update(['status' => $status]);
                break;
            case 7:
                $result = GirlImg::where('id', $id)->update(['status' => $status]);
                break;
            case 8:
                $result = Slide::where('id', $id)->update(['status' => $status]);
                break;
            default:
                $result = false;
        }
        if ($result) {
            return json(['status' => 1]);
        }
        return json(['status' => 0]);
    }

    /**
     * 更改排序
    1	资讯
    2	视频
    3	测评
    4	活动
    5	快讯
    6	音频
    7	图片
     * 8 品牌
     */
    public function updateSort(Request $request)
    {
        $sort = $request->param('sort');
        $id     = $request->param('id');
        $type   = $request->param('type');
        if (!is_numeric($sort)) {
            return json(['data' => '您输入的不是一个整数','code'=>500]);
        }

        switch ($type) {
            case 1:
                $result = Knowledge::where('id', $id)->update(['sort' => $sort]);
                break;
            case 2:
            case 6:
                $result = Forum::where('id', $id)->update(['sort' => $sort]);
                break;
            case 3:
                $result = Evaluation::where('id', $id)->update(['sort' => $sort]);
                break;
            case 4:
                $result = Active::where('id', $id)->update(['sort' => $sort]);
                break;
            case 5:
                $result = NewFlash::where('id', $id)->update(['sort' => $sort]);
                break;
            case 7:
                $result = GirlImg::where('id', $id)->update(['sort' => $sort]);
                break;
            case 8:
                $result = Brand::where('id', $id)->update(['sort' => $sort]);
                break;
            default:
                $result = false;
        }
        if ($result) {
            return json(['data' => $sort,'code'=>200]);
        }
        return json(['data' => 'error','code'=>500]);
    }


    /**
     * 获取对应模块id的标签
    1	资讯
    2	视频
    3	测评
    4	活动
    5	快讯
    6	音频
    7	图片
     */
    public function getLabel(Request $request)
    {
        $id   = $request->param('id');
        $type = $request->param('type');
        switch ($type) {
            case 1:
                $data = Knowledge::where('car_knowledge.id', $id)
                    ->field([
                        'car_knowledge.id',
                        'car_knowledge.label',
                    ])->find();
                break;
            case 2:
                $data = Forum::where(['id' => $id, 'is_video' => 1])->field([
                    'car_forum.id',
                    'car_forum.label',
                ])->find();
                break;
            case 3:
                $data = Evaluation::where('id', $id)->field([
                    'id',
                    'label_id as label',
                ])->find();
                break;
            case 5:
                $data = NewFlash::where('id', $id)->field([
                    'car_news_flash.id',
                    'car_news_flash.label_id as label',
                ])->find();
                break;

            default:
                $data = false;
        }


        $arr_label = [];

        if (!empty($data['label'])) {
            foreach (unserialize($data['label']) as $item => $value) {
                $arr_label[$item]['name'] = Label::where('id', $value)->value('name');
                $arr_label[$item]['id']   = Label::where('id', $value)->value('id');
            }
        }
        unset($data['label']);
        $data['label_data'] = array_values($arr_label);
        return json(array('code' => '200', 'info' => '已获取到数据', 'data' => $data));
    }


    /**
     * @return \think\response\Json
     * 获取menu排序
     */
    public function getMenuOther()
    {
        $menu     = [];

        $admin_id = Session::get('admin_id');
        $auth     = new Auth();

        $auth_rule_list = Db::name('auth_rule')->where('status', 1)->order(['sort' => 'DESC', 'id' => 'ASC'])->select();
        foreach ($auth_rule_list as $value) {
            if ($auth->check($value['name'], $admin_id) || $admin_id == 1) {
                $menu[] = $value;
            }
        }
        $menu = !empty($menu) ? array2tree($menu) : [];
        return json($menu);
    }

    public function excel()
    {
        $xlsName = "export";
        $xlsCell = array(
            array('id', '账号序列'),
            array('username', '名字'),
            array('username', '邮箱'),
        );
        $xlsData = User::where(1)->field(['id,username,username'])->limit(20)->select();
        exportExcel($xlsName, $xlsCell, $xlsData);
    }

    public function ipFind()
    {
        var_dump(Ip::find('171.12.10.156'));
    }

    /**
     * 找pid
     */
    public function getUrlPid(Request $request)
    {
        $url   = $request->param('url');

        $url   = empty(explode('.', $url)[0]) ? $url : explode('.', $url)[0];
        $url_1 = empty(explode('/', $url)[1]) ? $url : explode('/', $url)[1];
        $url_2 = empty(explode('/', $url)[2]) ? '' : explode('/', $url)[2];

        $where         = [];
        $where['name'] = ['like', "%$url%"];
        $auth_rule     = AuthRule::all();
        $find_id       = '';
        foreach ($auth_rule as $k => $v) {
            $find_url    = explode('/', $v['name']);
            $find_url[2] = empty($find_url[2]) ? '' : $find_url[2];

            if (($find_url[1] . '/' . $find_url[2]) == ($url_1 . '/' . $url_2)) {
                $find_id = $v['id'];
            }
        }

        if (!empty($find_id)) {
            $auth_rule = AuthRule::where(['id' => $find_id])->field(['id', 'pid'])->find();
            $top_id = $find_id;
        } else {
            $auth_rule = AuthRule::where($where)->field(['id', 'pid'])->find();
            $top_id = $auth_rule['id'];
        }

        if ($auth_rule['pid'] != 0) {
            $auth_rule_top = AuthRule::get($auth_rule['pid']);
            if ($auth_rule_top['pid'] != 0) {
                $auth_rule_top_2 = AuthRule::get($auth_rule_top['pid']);
                if ($auth_rule_top_2['pid'] != 0) {
                    $auth_rule_top_3 = AuthRule::get($auth_rule_top_2['pid']);
                    $find_id         = $auth_rule_top_3['id'];
                } else {
                    $find_id = $auth_rule_top_2['id'];
                }
            } else {
                $find_id = $auth_rule_top['id'];
            }
        } else {
            $find_id = $auth_rule['id'];
        }
        $data['top_id']  = empty($top_id) ? 178 : $top_id;
        $data['find_id'] = empty($find_id) ? 178 : $find_id;
        return json(['code' => 200, 'info' => '已获取到数据', 'data' =>  $data]);
    }
    /**
     * 根据id和type找对应的数据(预览)
     *
     * 1资讯
     * 2视频
     * 3测评
     * 4活动
     * 5快讯
     * 6音频
     * 7图片
     */
    public function getAllInfoByid(Request $request)
    {
        $id = $request->param('id');
        $type = $request->param('type');

        switch ($type) {
            case 1:
                $where = 'car_knowledge.id=' . $id;
                $data                = Knowledge::where($where)
                    ->join('car_knowledge_img', 'car_knowledge_img.knowledge_id = car_knowledge.id', 'LEFT')
                    ->field([
                        'car_knowledge.id',
                        'car_knowledge.title',
                        'car_knowledge_img.img_url',
                        'car_knowledge.lead',
                        'car_knowledge.source',
                        'car_knowledge.synopsis',
                        'car_knowledge.create_time',
                        'car_knowledge.browse_num',
                        'car_knowledge.speaker_name',
                        'car_knowledge.img',
                        'car_knowledge.label'
                    ])->find();
                $data['comment_num'] = Com::where('knowledge_id', $data['id'])->count('id');
                $arr_label           = [];
                if (empty($user_id)) {
                    $data['is_collect'] = 0;
                } else {
                    $data['is_collect'] = Follow::where([
                        'know_id' => $id,
                        'user_id' => $user_id
                    ])->find() ? 1 : 0;
                }


                if (!empty($data['label'])) {
                    foreach (unserialize($data['label']) as $item => $value) {
                        $label_arr['label_id']   = $value;
                        $label_arr['label_name'] = Label::where('id', $value)->value('name');
                        $arr_label[]             = $label_arr;
                    }
                }

                unset($data['label']);
                $data['label_name'] = $arr_label;

                break;
            case 2:
                $data    = ForumModel::where([
                    'car_forum.id' => $id,
                    'car_forum.is_video' => 1,
                ])->join('car_forum_media', 'car_forum_media.forum_id = car_forum.id', 'LEFT')
                    ->field(
                        [
                            'car_forum.id',
                            'car_forum.title',
                            'car_forum.source',
                            'car_forum.synopsis',
                            'car_forum.name',
                            'car_forum.cover',
                            'car_forum.create_time',
                            'car_forum.part_num',
                            'car_forum.label',
                            'car_forum.follow_num',
                            'car_forum_media.video_url',
                            'car_forum_media.video_size',
                            'car_forum_media.video_time',
                        ]
                    )->find();

                $data['label_name'] = unserializeLabel($data['label']);
                unset($data['label']);

                $data['share_num']   = Share::where('forum_id', $data['id'])->count();
                $data['comment_num'] = com::where('forum_id', $data['id'])->count();
                $data['is_collect']  = Follow::where([
                    'forum_id' => $data['id'],
                ])->find() ? 1 : 0;
                break;
            case 3:
                $eva_data = Evaluation::get($id);
                if ($eva_data['evaluation_type'] == 1) {//图文

                    $data                = Evaluation::where('id', $id)->field([
                        'car_evaluation.id',
                        'car_evaluation.headline',
                        'car_evaluation.source',
                        'car_evaluation.content',
                        'car_evaluation.author',
                        'car_evaluation.number_play',
                        'car_evaluation.avatar',
                        'car_evaluation.label_id',
                        'car_evaluation.create_time',
                    ])->find();
                    $data['comment_num'] = Com::where('evaluation_id', $id)->count('id');

                    $arr_label = [];
                    if (empty($user_id)) {
                        $data['is_collect'] = 0;
                    } else {
                        $data['is_collect'] = Follow::where([
                            'eval_id' => $id,
                            'user_id' => $user_id
                        ])->find() ? 1 : 0;
                    }


                    if (!empty($data['label'])) {
                        foreach (unserialize($data['label']) as $item => $value) {
                            $label_arr['label_id']   = $value;
                            $label_arr['label_name'] = Label::where('id', $value)->value('name');
                            $arr_label[]             = $label_arr;
                        }
                    }
                    unset($data['label_id']);
                    $data['label_name'] = $arr_label;

                }
                if ($eva_data['evaluation_type'] == 2) { //视频
                    $data = Evaluation::where('id', $id)->field([
                        'car_evaluation.id',
                        'car_evaluation.headline as title',
                        'car_evaluation.source',
                        'car_evaluation.content as synopsis',
                        'car_evaluation.author as name',
                        'car_evaluation.video_pic as cover',
                        'car_evaluation.number_play as part_num',
                        'car_evaluation.avatar',
                        'car_evaluation.label_id',
                        'car_evaluation.video_time',
                        'car_evaluation.video_url',
                        'car_evaluation.video_size',
                        'car_evaluation.create_time',
                    ])->find();

                    $data['label_name'] = unserializeLabel($data['label_id']);
                    unset($data['label_id']);
                    $data['share_num']   = Share::where('evaluation_id', $id)->count();
                    $data['comment_num'] = com::where('evaluation_id', $id)->count();
                    $data['follow_num']  = Follow::where('eval_id', $id)->count();

                    if (empty($user_id)) {
                        $data['is_collect'] = 0;
                    } else {
                        $data['is_collect'] = Follow::where([
                            'eval_id' => $id,
                            'user_id' => $user_id
                        ])->find() ? 1 : 0;
                    }
                }
                break;
            case 5:
                $user_id = $request->param('user_id') ?: 0;

                $data = NewFlash::where('car_news_flash.id', $id)
                    ->field(['name', 'index_column_id', 'author', 'content', 'label_id', 'id'])
                    ->find();


                $data['index_column_name'] = IndexColumn::where('id', $data['index_column_id'])->value('column_name');
                $data['commnet_num']       = Com::where('news_flash_id', $data['id'])->count('car_com.id') ?: 0;

                if ($user_id) {
                    $data['is_collect'] = Follow::where([
                        'news_flash_id' => $data['id'],
                        'user_id' => $user_id
                    ])->find() ? 1 : 0;

                } else {
                    $data['is_collect'] = 0;
                }
                $label_arr = [];
                if (!empty($data['label_id'])) {
                    foreach (unserialize($data['label_id']) as $item => $value) {
                        $label_arr['label_id']   = $value;
                        $label_arr['label_name'] = Label::where('id', $value)->value('name');
                        $arr_label[]             = $label_arr;
                    }
                    $data['label_arr'] = $arr_label;
                } else {
                    $data['label_arr'] = [];
                }

                unset($data['label_id']);
                break;

            default:
                $data = false;

        }

    }



    /**
     * 更改评论状态
     */
    public function changeComStatus(Request $request)
    {

        $status = $request->param('status');
        $id = $request->param('id');
        $result = Com::where('id', $id)->update(['status' => $status]);
        if ($result) {
            return json(['status' => 1]);
        }
        return json(['status' => 0]);

    }
    

    /**
     * 预览首页
     */

    public function getImgByName(Request $request)
    {
        $name           = $request->param('name') ?: '车乎';
        $where['title'] = ['like', "%{$name}%"];
        $data           = Material::where($where)->field(['id', 'img_url'])->find();
        if (empty($data)) {
            return json(['code' => 500, 'info' => '没有数据']);
        }
        return json(['code' => 200, 'info' => '已获取到数据', 'data' => $data]);
    }


}